/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-04-20
*/
package com.rzico.core.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysReport;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysReportService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.util.CodeGenerator;
import com.rzico.util.FreemarkerUtils;
import com.rzico.util.HttpUtils;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.jasperreports.engine.JRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计报表控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-04-20
 */
@Api(description = "统计报表接口")
@RestController
@RequestMapping("/admin/sysReport")
public class SysReportController extends BaseController {

    @Autowired
    private SysReportService sysReportService;

    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private SysUserService sysUserService;

//    @Autowired
//    private EnterpriseService enterpriseService;


    @Value("${rzico.filePath.windows}")
    private String windowsFilePath;

    @Value("${rzico.filePath.linux}")
    private String linuxFilePath;

    /**
     * 分页查询统计报表
     *
     * @return
    */
    @ApiOperation("分页查询统计报表")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "name", value = "报表名称", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "reportCategoryId", value = "结束时间", dataType = "String", paramType = "query")
    })
    public CommResult<SysReport> list(String name, String reportCategoryId, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(name)){
            params.put("name", name);
        }
        if (StringUtils.isNotEmpty(reportCategoryId)){
            params.put("treePath", reportCategoryId);
        }

        SysUser sysUser = sysUserService.getCurrent();
        if (sysUser==null) {
            return CommResult.error("没有登录");
        }
        params.put("mchId",sysUser.getMchId());

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<SysReport> list = sysReportService.selectList(params);
        PageResult<SysReport> pageResult = new PageResult<SysReport>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }


    /**
     * 获取报表模块列表
     *
     * @return
     */
    @ApiOperation("获取报表模块列表")
    @GetMapping("/templateList")
    @ApiImplicitParams({@ApiImplicitParam(name = "name", value = "报表名称", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "reportCategoryId", value = "结束时间", dataType = "String", paramType = "query")
    })
    public CommResult<SysReport> templateList(String name, String reportCategoryId, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(name)){
            params.put("name", name);
        }
        if (StringUtils.isNotEmpty(reportCategoryId)){
            params.put("treePath", reportCategoryId);
        }

        SysUser sysUser = sysUserService.findByUsername("admin");
        if (sysUser==null) {
            return CommResult.error("没有登录");
        }
        params.put("mchId",sysUser.getMchId());

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<SysReport> list = sysReportService.selectList(params);
        PageResult<SysReport> pageResult = new PageResult<SysReport>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条统计报表
     *
     * @return
    */
    @ApiOperation("查询单条统计报表")
    @GetMapping("/find/{id}")
    public CommResult<SysReport> find(@PathVariable String id) {
        SysReport result = sysReportService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("sysReport",result);
        return CommResult.success(data);

    }

    /**
     * 保存统计报表
     *
     * @param sysReport
     * @return
     */
    @ApiOperation("保存统计报表")
    @PostMapping("/save")
    public CommResult<SysReport> save(@RequestBody SysReport sysReport) {
        sysReport.setId(CodeGenerator.getUUID());
        sysReport.setCreateDate(new Date());
        sysReport.setModifyDate(sysReport.getCreateDate());
        sysReport.setDelFlag(false);
        SysUser sysUser = sysUserService.getCurrent();
        if (sysUser!=null) {
            sysReport.setMchId(sysUser.getMchId());
        }
        int affectCount = sysReportService.insert(sysReport);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        SysReport result = sysReportService.findById(sysReport.getId());
        return CommResult.success(result);

    }


    /**
     * 添加统计报表
     *
     * @param ids
     * @return
     */
    @Log(desc = "添加统计报表", type = Log.LOG_TYPE.DEL)
    @ApiOperation("添加统计报表,ids用逗号拼接")
    @PostMapping("/add/{ids}")
    public CommResult<SysReport> add(@PathVariable String ids) {
        SysUser sysUser = sysUserService.getCurrent();

        for (String id:ids.split(",")) {

            SysReport sysReport = sysReportService.selectByPrimaryKey(id);

            SysReport report = new SysReport();
            report.setCreateDate(new Date());
            report.setId(CodeGenerator.getUUID());
            report.setDelFlag(false);
            report.setMchId(sysUser.getMchId());
            report.setName(sysReport.getName());
            report.setTemplate(sysReport.getTemplate());
            report.setThumbnail(sysReport.getThumbnail());
            report.setParams(sysReport.getParams());
            report.setStatus(sysReport.getStatus());
            report.setReportCategoryId(sysReport.getReportCategoryId());
            report.setSql(sysReport.getSql());
            report.setRemark(sysReport.getRemark());
            sysReportService.insert(report);


        }

        return CommResult.success();
    }

    /**
     * 批量删除统计报表
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除统计报表", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除统计报表,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<SysReport> del(@PathVariable String ids) {

        sysReportService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新统计报表
     *
     * @param sysReport
     * @return
     */
    @Log(desc = "更新统计报表", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新统计报表")
    @PostMapping("/update")
    public CommResult<SysReport> update(@RequestBody SysReport sysReport) {
        sysReport.setModifyDate(new Date());
        int affectCount = sysReportService.updateByPrimaryKeySelective(sysReport);
        if (affectCount <= 0){
            return CommResult.error();
        }
        SysReport result = sysReportService.findById(sysReport.getId());
        return CommResult.success(result);
    }

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date(2020, 06, 14);

        System.out.println(sdf.format(date));
    }
}
